package com.sgj.controller;

import com.sgj.pojo.Comment;
import com.sgj.pojo.User;
import com.sgj.service.BlogService;
import com.sgj.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * @author 沈国纪
 * @date 2021/4/4 18:59
 */
@Controller
public class CommentController {

	@Autowired
	private CommentService commentService;

	@Autowired
	private BlogService blogService;

	@Value("${comment.avatar}")
	private String avatar;

	/**
	 * 根据博客 id 查询所有留言信息
	 * @param blogId
	 * @param model
	 * @return
	 */
	@GetMapping("/comments/{blogId}")
	public String comments(@PathVariable Long blogId, Model model) {
		model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
		return "blog :: commentList";
	}

	/**
	 * 添加留言信息
	 * @param comment
	 * @param session
	 * @return
	 */
	@PostMapping("/comments")
	public String post(Comment comment, HttpSession session) {
		Long blogId = comment.getBlog().getId();
		comment.setBlog(blogService.getBlog(blogId));
		User user = (User) session.getAttribute("user");
		// 判断回复的用户是否为管理员
		if (Objects.nonNull(user)) {
			comment.setAvatar(user.getAvatar());
			comment.setAdminComment(true);
		} else {
			comment.setAvatar(avatar);
		}
		commentService.saveComment(comment);
		return "redirect:/comments/" + blogId;
	}
}
